package com.application.chiettinhdienluc.utils;  

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.application.chiettinhdienluc.data.GlobalData;

import android.os.Build;
import android.os.Environment;


public class AlbumUtil {

	private String mCurrentPhotoPath;

	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;

	//private Context mContext = null;

	private volatile static AlbumUtil albumUtil;
	
	public static AlbumUtil getInstance()
	{	
		if(albumUtil == null)
		{
			synchronized (AlbumUtil.class) {
				if (albumUtil == null) {
					albumUtil = new AlbumUtil();
				}
			}			
		}
		return albumUtil;
	}	

	public AlbumUtil() {		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

//			File routesRoot = Environment.getExternalStorageDirectory();
			String folderPath = GlobalData.sdcardPath + "/ChietTinh" ;
			storageDir = new File(folderPath);
//			storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());

//			if (storageDir != null) {
//				if (! storageDir.mkdirs()) {
//					if (! storageDir.exists()){
//						Log.d("AlbumUtil", "failed to create directory");
//						return null;
//					}
//				}
//			}
//			if(routesRoot.canRead() && routesRoot.canWrite())
//			{
//				Log.w("Here: ", "11111111111111111");
//			}
//			else
//				Log.w("Here: ", "22222222222222222");
			
			if (storageDir != null) {
				if (!storageDir.exists())	
				{
					if (!storageDir.mkdir())
					{
						if(!storageDir.mkdirs())
						{
							Log.d("AlbumUtil", "failed to create directory");
							return null;
						}
					} 
				}
			}
		} else {
			Log.v("AlbumUtil", "External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
		return imageF;
	}

	public File setUpPhotoFile() throws IOException {		
		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();		
		return f;
	}

}
